package com.simou.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

// mybatis-plus自动填充公共属性
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]");
        // 若数据表不存在该属性，不自动填充
        if(hasField(metaObject,"createTime")){
            metaObject.setValue("createTime",LocalDateTime.now());
        }
        if(hasField(metaObject,"updateTime")){
            metaObject.setValue("updateTime",LocalDateTime.now());
        }
        if(hasField(metaObject,"createUser")){
            metaObject.setValue("createUser",BaseContext.getCurrentId());
        }
        if(hasField(metaObject,"updateUser")){
            metaObject.setValue("updateUser",BaseContext.getCurrentId());
        }
        if(hasField(metaObject,"orderTime")){
            metaObject.setValue("orderTime",LocalDateTime.now());
        }
        if(hasField(metaObject,"checkoutTime")){
            metaObject.setValue("checkoutTime",LocalDateTime.now());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]");
        metaObject.setValue("updateTime",LocalDateTime.now());
        metaObject.setValue("updateUser",BaseContext.getCurrentId());
    }

    private boolean hasField(MetaObject metaObject,String field){
        return metaObject.hasSetter(field)&&metaObject.hasGetter(field);
    }
}
